﻿using System;
using System.Security.Cryptography;
using CloudShot.Core.Utils;
using Newtonsoft.Json;

namespace CloudShot.Core.Converters.Json
{
  /// <summary>
  /// Serializes any object to encrypted string, using <see cref="ProtectedData"/>class. 
  /// Writes in JSON that string in base64 representation. 
  /// Object for serialization should be marked with SerializableAttribute.
  /// </summary>
  public class SecureJsonConverter : JsonConverter
  {
    private readonly DataProtectionScope _protectionScope;

    public SecureJsonConverter(DataProtectionScope protectionScope = DataProtectionScope.CurrentUser)
    {
      _protectionScope = protectionScope;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      if (value == null)
        return;

      string data = Base64Utils.SerializeToBase64(value);
      string encryptedData = data.EncryptString(_protectionScope);

      writer.WriteValue(encryptedData);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
      var encryptedData = serializer.Deserialize<string>(reader);

      if (string.IsNullOrEmpty(encryptedData))
        return encryptedData;

      var data = encryptedData.DecryptString(_protectionScope);

      return Base64Utils.DeserializeFromBase64<object>(data);
    }

    public override bool CanConvert(Type objectType)
    {
      return true;
    }
  }
}